package javassist;

import com.thghh.bcode.compiler.DynamicJavaCompiler;
import com.thghh.bcode.compiler.JavacJavaCompiler;
import com.thghh.bcode.decompiler.DynamicClassDecompiler;

import java.io.DataOutputStream;
import java.io.IOException;

/**
 * @author Zhikang.Peng
 * @version 1.0
 * @email thghh@qq.com
 * @date 2020/12/3 10:04
 */
public class ForwardingCtClass extends CtClassType {

    private CtClass ctClass;
    private DynamicClassDecompiler decompiler;
    private DynamicJavaCompiler compiler;

    public ForwardingCtClass(CtClass ctClass) {
        super(ctClass.getClassFile(), ctClass.getClassPool());
        this.ctClass = ctClass;
        decompiler = new DynamicClassDecompiler();
        compiler = new JavacJavaCompiler();
    }

    @Override
    public void toBytecode(DataOutputStream out) throws CannotCompileException, IOException {
        byte[] bytecode = ctClass.toBytecode();
        String sourceCode = decompiler.decompiler(bytecode);
        compiler.javaCompiler(ctClass.getName(), sourceCode);
        out.write(compiler.getByteCode());
        out.flush();
    }

    @Override
    public byte[] toBytecode() throws IOException, CannotCompileException {
        byte[] bytecode = ctClass.toBytecode();
        String sourceCode = decompiler.decompiler(bytecode);
        compiler.javaCompiler(ctClass.getName(), sourceCode);
        return compiler.getByteCode();
    }

    @Override
    public Class<?> toClass() throws CannotCompileException {
        try {
            return compiler.loadClass(ctClass.getName());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
